﻿using System.Reflection;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.Extensions.DependencyInjection;

namespace SBlogCore.Common.FluentValidatorExtend
{
    public static class FluentValidatorSetup
    {
        /// <summary>
        /// 注册Fluent
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies"></param>
        /// <returns></returns>
        public static IServiceCollection AddFluentValidatorSetup(this IServiceCollection services, IEnumerable<Assembly> assemblies)
        {
            services.AddFluentValidationAutoValidation();
            //GetGenericTypeDefinition():获取构造当前泛型的泛型类型
            var types = assemblies.SelectMany(s => s.GetTypes())
                .Where( w => w.BaseType is {IsGenericType: true} && w.BaseType.GetGenericTypeDefinition()== typeof(SblogCoreAbstractValidator<>)).ToList();
            foreach (var type in types)
            {
                if (type.BaseType?.BaseType != null && type.BaseType.GetGenericArguments().Length>0)
                {
                    services.AddSingleton(typeof(IValidator<>).MakeGenericType(type.BaseType.GetGenericArguments().First()), type);
                }
            }
            return services;
        }
    }
}
